<?php

namespace common\models\trade;

use Yii;

/**
 * This is the model class for table "{{%partner}}".
 *
 * @property int $id
 * @property string $name 商户名称
 * @property string $app_id 商户应用ID
 * @property string $description 商户名称
 * @property string $sign 签名
 * @property string $expire_time 签约到期时间
 * @property int $status 商户状态：-1取消，0未支付，1已支付
 * @property string $created_at 创建时间
 * @property string $updated_at 更新时间
 */
class Partner extends \common\db\ActiveRecord {

    use \common\traits\Constants;
    use \common\traits\TimestampBehavior;

    const STATUS_DELETED = 0;
    const STATUS_ACTIVE = 10;

    /**
     * @inheritdoc
     */
    public static function tableName() {
        return '{{%trade_partner}}';
    }

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['name', 'app_id', 'sign'], 'required'],
            [['expire_time', 'status', 'created_at', 'updated_at'], 'integer'],
            [['name', 'sign'], 'string', 'max' => 64],
            [['app_id'], 'string', 'max' => 16],
            [['description'], 'string', 'max' => 255],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'name' => '商户名称',
            'app_id' => '商户应用ID',
            'description' => '商户名称',
            'sign' => '签名',
            'expire_time' => '签约到期时间',
            'status' => '商户状态：-1取消，0未支付，1已支付',
            'created_at' => '创建时间',
            'updated_at' => '更新时间',
        ];
    }

    /**
     * Finds user by username
     *
     * @param string $username
     * @return static|null
     */
    public static function findByAppId($appid) {
        return static::findOne(['app_id' => $appid, 'status' => self::STATUS_ACTIVE]);
    }

    public function getTrade() {
        return $this->hasMany(Trade::className(), ['partner_id' => 'id'])->inverseOf('trade');
    }

    /**
     * @return array
     */
    public static function activeList() {
        $data = static::find()->all();
        $list = [];
        foreach ($data as $item) {
            $list[$item->id] = $item->name . '(' . $item->app_id . ')';
        }
        return $list;
    }

}
